//
// Created by user on 2025/7/31.
//

#ifndef HELLOC_MUTEX_H
#define HELLOC_MUTEX_H

#include "systemc.h"


class Mutex : public sc_module {
public:
    sc_mutex mtx;

    Mutex(sc_module_name name) : sc_module(name) {
        SC_THREAD(thread1);
        SC_THREAD(thread2);
    }


    void thread1(){
        while(true) {
            if(mtx.trylock() == -1){
                mtx.lock();
                std::cout << sc_time_stamp() << "thread1 obtained resource by lock()" << std::endl;
            } else {
                std::cout << sc_time_stamp() << "thread1 obtained resource by trylock()" << std::endl;
            }
            wait(1,SC_SEC);
            mtx.unlock();
            std::cout << sc_time_stamp() << "thread1 released resource" << std::endl;
            wait(SC_ZERO_TIME);
        }

    }

    void thread2(){
        while(true) {
            if(mtx.trylock() == -1){
                mtx.lock();
                std::cout << sc_time_stamp() << "thread2 obtained resource by lock()" << std::endl;
            } else {
                std::cout << sc_time_stamp() << "thread2 obtained resource by trylock()" << std::endl;
            }
            wait(1,SC_SEC);
            mtx.unlock();
            std::cout << sc_time_stamp() << "thread2 released resource" << std::endl;
            wait(SC_ZERO_TIME);
        }
    }



};
#endif //HELLOC_MUTEX_H
